import { Injectable } from '@nestjs/common';
import { DbService } from 'apps/admin/src/db/db.service';
import CreateDto from './dto/create.dto';
import UpdateDto from './dto/update.dto';
import { DictionaryItem } from '@app/db/common/entity/DictionaryItem';

@Injectable()
export class DictionaryItemService {
    constructor(
        private readonly db:DbService
    ){}


    async add(dto:CreateDto) {
        if((await this.db.dictionaryItem.isExistsByWhere({name : dto.name, categoryId : dto.categoryId, parentId : dto.parentId}))) throw new Error('已存在相同的名称')
        if((await this.db.dictionaryItem.isExistsByWhere({code : dto.code, categoryId : dto.categoryId, parentId : dto.parentId}))) throw new Error('已存在相同的编码')
        
        return this.db.dictionaryItem.insert(dto)
    }

    async update(dto:UpdateDto) {
        const item = await this.db.dictionaryItem.findOne({id : dto.id})
        if(!item) return false
        let updateData:{[key in keyof DictionaryItem]? : DictionaryItem[key]} = {}
        if(item.name != dto.name) {
            updateData.name = dto.name
        }


        if(item.code.toLocaleLowerCase() != dto.code.toLocaleLowerCase()) {
            updateData.code = dto.code
        }

        if((Object.keys(updateData)).length == 0) return true


        if(updateData.name && (await this.db.dictionaryItem.isExistsByWhere({name : dto.name, categoryId: item.categoryId, parentId: item.parentId}))) throw new Error('已存在相同的名称')
        if(updateData.code && (await this.db.dictionaryItem.isExistsByWhere({code : dto.code, categoryId: item.categoryId, parentId: item.parentId}))) throw new Error('已存在相同的编码')

        return this.db.dictionaryItem.update({id : dto.id}, dto)
    }

    async del(id:number) {
        if((await this.db.dictionaryItem.isExistsByWhere({categoryId : id}))) throw new Error('该分类存在子分类，不可删除')
        return this.db.dictionaryItem.delete({id : id})
    }



    async getItemByCategory(categoryCode:string) {
        const category = await this.db.dictionaryCategory.findOne({code : categoryCode}, ['id'])
        if(!category) return []

        return this.db.dictionaryItem.find({categoryId : category.id})
    }

    async getItemCodeToNameByCategory(categoryCode:string) {
        const map:{[key:string] : string|number} = {}
        const items = await this.getItemByCategory(categoryCode)
        items.forEach(item => {
            map[item.code] = item.name
        })

        return map
    }

    async getItemNameToCodeByCategory(categoryCode:string) {
        const map:{[key:string] : string|number} = {}
        const items = await this.getItemByCategory(categoryCode)
        items.forEach(item => {
            map[item.name] = item.code
        })

        return map
    }
}
